package com.example.gryoshare

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Bundle
import android.view.Choreographer
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.gryoshare.ui.theme.GRYOSHARETheme
import io.ktor.network.sockets.SocketOptions
import io.ktor.server.application.install
import io.ktor.server.engine.ApplicationEngine
import io.ktor.server.engine.EmbeddedServer
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.routing.routing
import io.ktor.server.websocket.DefaultWebSocketServerSession
import io.ktor.server.websocket.WebSocketServerSession
import io.ktor.server.websocket.WebSockets
import io.ktor.server.websocket.webSocket
import io.ktor.websocket.Frame
import io.ktor.websocket.send
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import java.util.Collections
import java.util.concurrent.CopyOnWriteArraySet

class MainActivity : ComponentActivity(), SensorEventListener {
    var xyz by mutableStateOf(FloatArray(3))
    var sensor: Sensor? = null
    lateinit var sensorManager: SensorManager
    var portText by mutableStateOf("9876")
    var isBroad by mutableStateOf(false)
    var sessions = Collections.synchronizedSet(LinkedHashSet<DefaultWebSocketServerSession>())
    var server: EmbeddedServer<*, *>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR)
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            GRYOSHARETheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Column(
                        modifier = Modifier
                            .padding(innerPadding)
                            .fillMaxSize()
                            .verticalScroll(rememberScrollState())
                    ) {
                        DashBoard(
                            xyz = xyz,
                            modifier = Modifier.padding(16.dp)
                        )
                        Spacer(Modifier.height(24.dp))
                        OutlinedTextField(
                            value = portText,
                            onValueChange = { portText = it.filter { c -> c.isDigit() } },
                            label = { Text("PORT") },
                            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                            singleLine = true,
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(horizontal = 24.dp)
                        )
                        Spacer(Modifier.height(16.dp))
                        Button(
                            onClick = {
                                val port = portText.toIntOrNull()
                                if (port == null) {
                                    Toast.makeText(
                                        this@MainActivity,
                                        "WRONG PORT",
                                        Toast.LENGTH_SHORT
                                    )
                                        .show()
                                    return@Button
                                }
                                isBroad = !isBroad
                                if (isBroad) {
                                    startBroadcast(port)
                                } else {
                                    stopBroadcast()
                                }
                            },
                            modifier = Modifier
                                .padding(horizontal = 24.dp)
                                .align(Alignment.CenterHorizontally)
                        ) {
                            Text(
                                if (isBroad) "停止广播" else "启动广播",
                            )
                        }
                    }
                }
            }
        }
    }

    fun startBroadcast(port: Int) {
        server = embeddedServer(Netty, port = port) {
            install(WebSockets)
            routing {
                webSocket("/sensor") {
                    sessions.add(this)
                    try {
                        for (frame in incoming) {
                            if (frame is Frame.Close) break
                        }
                    } finally {
                        sessions.remove(this)
                    }
                }
            }
        }.start(wait = false)
    }

    fun stopBroadcast() {
        server?.stop(500, 1000)
        server = null
        sessions.clear()
    }

    override fun onResume() {
        super.onResume()
        sensor?.also {
            sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_GAME)
        }
    }

    override fun onPause() {
        super.onPause()
        sensorManager.unregisterListener(this)
    }

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
    }

    override fun onSensorChanged(event: SensorEvent?) {
        if (event?.sensor?.type == Sensor.TYPE_GAME_ROTATION_VECTOR) {
            xyz = floatArrayOf(event.values[0], event.values[1], event.values[2])
            var now = System.currentTimeMillis()
            val bytes = Json.encodeToString(
                RotationEvent(
                    xyz[0],
                    xyz[1],
                    xyz[2],
                    now
                )
            ).toByteArray()
            GlobalScope.launch(Dispatchers.IO) {
                val iter = sessions.iterator()
                while (iter.hasNext()) {
                    val sess = iter.next()
                    try {
                        sess.send(bytes)   // 现在处于协程体内，可以挂起
                    } catch (e: Exception) {
                        iter.remove()
                    }
                }

            }
        }
    }
}

@Composable
fun DashBoard(
    xyz: FloatArray,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(horizontal = 32.dp),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        AxisBar(label = "X", value = xyz[0])
        AxisBar(label = "Y", value = xyz[1])
        AxisBar(label = "Z", value = xyz[2])
    }
}

@Composable
fun AxisBar(label: String, value: Float) {
    val coerced = value.coerceIn(-1f, 1f)
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        Text(
            text = "$label = ${"%.3f".format(value)}",
            style = MaterialTheme.typography.bodyLarge,
            modifier = Modifier.padding(6.dp)
        )
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(12.dp)
        ) {
            Row(
                modifier = Modifier.weight(1f),
                horizontalArrangement = Arrangement.End
            ) {
                if (coerced < 0) {
                    Box(
                        modifier = Modifier
                            .fillMaxHeight()
                            .fillMaxWidth((-coerced))
                            .background(Color.Green)
                    )
                }
            }
            Row(
                modifier = Modifier.weight(1f)
            ) {
                if (coerced > 0) {
                    Box(
                        modifier = Modifier
                            .fillMaxHeight()
                            .fillMaxWidth(coerced)
                            .background(Color.Green)
                    )
                }
            }
        }
    }
}